<?php

class App_Helper_Html {
   
   protected $_str ="";
   protected $_attribs = array();
   protected $_tagName = 'a';
   protected $_data = '';
   
   public function __construct($tagName, $data, $attribs=array()) {
      $this->_tagName = $tagName;
      $this->_data = $data;
      $this->_attribs = array_merge($this->_attribs, $attribs);
   }
   
   public function __set($name, $value) {
      $this->_attribs[$name] = $value;
   }
   
   public function __get($name) {
      if(isset($this->_attribs[$name])) {
         return $this->_attribs[$name];
      }
   }
   
   public function __call($name, $arguments) {
      
      if(strstr($name, 'set') || strstr($name, 'get')) {
         preg_match('/(set)(\w+)|(get)(\w+)/', $name, $m);
         foreach($m as $k => &$v) {
            if(strlen(trim($v)) > 0) {
               $m2[] = $v;
            }
         }
         $attrib = strtolower($m2[2]);
         if($m2[1] == 'get' && in_array($attrib, $this->_attribs)) {
            return $this->_attribs[$attrib];
         } else if($m2[1] == 'set') {
            $this->_attribs[$attrib] = $arguments[0];
         }
      }
   }
   
   public function __toString() {
      $str = "<{$this->_tagName}";
      foreach($this->_attribs as $name => $val) {
         $str .= " $name=\"$val\"";
      }
      if($this->_data) {
         $str .= ">" . $this->_data . "</{$this->_tagName}>";
      } else {
         $str .= " />";
      }
      
      return $str;
   }
   
   public function replaceTag($tag, $text, $start='', $end='', $leaveContent=true) {
      // [url]here[/url] > <a href="somelink">here</a>"
      
      $pattern = sprintf('/(\[%s\])([^\]\[]+)([\[\/%s\]]+)/i', $tag, $tag);
      $text = preg_replace($pattern, "$start" . ($leaveContent ? '$2' : '') . $end, $text);
      
      return $text;
      
   }
   
   
}